package com.whh.starter.web.interceptor;


import com.whh.starter.properties.CorsProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 跨域拦截器
 * 除此之外还有很多种方式
 * 1. Spring Cors
 *  @see org.springframework.web.filter.CorsFilter
 * 2. @CrossOrigin 注解
 * @see org.springframework.web.bind.annotation.CrossOrigin
 * 3. WenMvcConfigurer#addCorsMappings
 * @see org.springframework.web.servlet.config.annotation.WebMvcConfigurer#addCorsMappings
 * 4. 前后端同一个服务，同域名，同端口，同协议
 *
 */
@Component
@EnableConfigurationProperties(CorsProperties.class)
public class CORSInterceptor implements HandlerInterceptor {

    private final CorsProperties corsProperties;

    public CORSInterceptor(CorsProperties CorsProperties) {
        this.corsProperties = CorsProperties;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        matchOrigin(request, response);
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
//        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        if (request.getMethod().equals(RequestMethod.OPTIONS.name())){
            response.setStatus(HttpStatus.OK.value());
            return false;
        }
        return true;
    }

    private void matchOrigin(HttpServletRequest request, HttpServletResponse response) {
        if("*".equals(corsProperties.getAllowOrigin())){
            response.setHeader("Access-Control-Allow-Origin", corsProperties.getAllowOrigin());
            return;
        }
        String origin =request.getHeader("Origin");
        if (origin != null){
            String[] origins = corsProperties.getAllowOrigin().split(",");
            for (String allowOrigin : origins) {
                if (allowOrigin.equals(origin)){
                    response.setHeader("Access-Control-Allow-Origin", origin);
                    return;
                }
            }
        }
    }
}
